package com.kmproject.haifu.mvp.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.flyco.roundview.RoundTextView;
import com.jess.arms.base.BaseFragment;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.kmproject.haifu.R;
import com.kmproject.haifu.app.utils.CustomGridItemDecoration;
import com.kmproject.haifu.app.utils.ViewExtensionKt;
import com.kmproject.haifu.di.component.DaggerFollowListComponent;
import com.kmproject.haifu.di.module.FollowListModule;
import com.kmproject.haifu.mvp.contract.FollowListContract;
import com.kmproject.haifu.mvp.model.entity.beans.UserAttentionBean;
import com.kmproject.haifu.mvp.model.entity.resbean.ReqParamsAttentionAdd;
import com.kmproject.haifu.mvp.model.entity.resbean.ReqParamsAttentionCancel;
import com.kmproject.haifu.mvp.model.entity.resbean.ReqParamsGetFollowList;
import com.kmproject.haifu.mvp.presenter.FollowListPresenter;
import com.kmproject.haifu.mvp.ui.activity.MyStoreActivity;
import com.kmproject.haifu.mvp.ui.activity.PersonalHomePageActivity;
import com.kmproject.haifu.mvp.ui.adapter.BaseRecyclerAdapter;
import com.kmproject.haifu.mvp.ui.holder.SmartViewHolder;
import com.kmproject.haifu.mvp.ui.widget.pullRefresh.OnRefreshLoadMoreListener2;
import com.kmproject.haifu.mvp.ui.widget.pullRefresh.PullToRefreshView;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;

import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * 关注列表
 */
public class FollowListFragment extends BaseFragment<FollowListPresenter> implements FollowListContract.View {
    @BindView(R.id.srl_follow_list)
    PullToRefreshView srl_follow_list;
    @BindView(R.id.rv_follow_list)
    RecyclerView rv_follow_list;
    @BindView(R.id.i_empty)
    View empty;
    private static final String TAB_FLAG = "tabFlag";
    private static final String USER_ID = "userId";
    private static final String IS_CURRENT_USER = "isCurrentUser";
    private int tabFlag;
    private String userId;
    private boolean isCurrentUser;//是否当前用户

    private ReqParamsGetFollowList reqParams;
    private BaseRecyclerAdapter<UserAttentionBean> adapter;

    public static FollowListFragment newInstance(int tabFlag, String userId, boolean isCurrentUser) {
        FollowListFragment fragment = new FollowListFragment();
        Bundle args = new Bundle();
        args.putInt(TAB_FLAG, tabFlag);
        args.putString(USER_ID, userId);
        args.putBoolean(IS_CURRENT_USER, isCurrentUser);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void setupFragmentComponent(AppComponent appComponent) {
        DaggerFollowListComponent
                .builder()
                .appComponent(appComponent)
                .followListModule(new FollowListModule(this))//请将FollowListModule()第一个首字母改为小写
                .build()
                .inject(this);
    }

    @Override
    public View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_follow_list, container, false);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        reqParams = new ReqParamsGetFollowList();
        if (getArguments() != null) {
            tabFlag = getArguments().getInt(TAB_FLAG);
            userId = getArguments().getString(USER_ID);
            isCurrentUser = getArguments().getBoolean(IS_CURRENT_USER);
        }

        if (isCurrentUser) {
            reqParams.setType(0);
        } else {
            reqParams.setType(1);
            reqParams.setUserId(userId);
        }

        rv_follow_list.addItemDecoration(new CustomGridItemDecoration.Builder(Objects.requireNonNull(getContext())).setVerticalSpan(0f).
                setHorizontalSpan(1f).setColor(ContextCompat.getColor(getContext(), R.color.common_menu_text)).setShowLastLine(false).build());
        ArmsUtils.configRecyclerView(rv_follow_list, new LinearLayoutManager(getContext()));
        rv_follow_list.setItemAnimator(new DefaultItemAnimator());
        srl_follow_list.setEnableRefresh(true);
        srl_follow_list.setEnableAutoLoadMore(false);
        srl_follow_list.setEnableHeaderTranslationContent(true);

        //0-个人；1-店铺
        switch (tabFlag) {
            case 0: {
                adapter = new BaseRecyclerAdapter<UserAttentionBean>(R.layout.item_follow_user) {
                    @Override
                    protected void onBindViewHolder(SmartViewHolder holder, UserAttentionBean model, int position) {
                        holder.image(R.id.imv_user_head_portrait, model.getAvatar());
                        holder.image(R.id.imv_level_icon, model.getMemberLevelHeadImage());
                        holder.text(R.id.tv_user_name, model.getNickName());
                        StringBuilder sb = new StringBuilder();
                        // 拼接注册时间/性别/状态
                        sb.append(model.getRegisterLongTime());
                        sb.append(model.getUserSex());
                        sb.append(model.getOnlineStatus());
                        holder.text(R.id.tv_user_base_info, sb);
                        RoundTextView rtv_operation = (RoundTextView) holder.findViewById(R.id.rtv_operation);
                        if (model.getIsAttention() == 1) {// 已关注
                            rtv_operation.getDelegate().setBackgroundColor(ContextCompat.getColor(Objects.requireNonNull(getContext()), R.color.color_AAAAAA));
                            rtv_operation.setTextColor(ContextCompat.getColor(getContext(), R.color.white));
                            rtv_operation.setText(getString(R.string.is_followed));
                        } else {
                            rtv_operation.getDelegate().setBackgroundColor(ContextCompat.getColor(Objects.requireNonNull(getContext()), R.color.color_F9D35A));
                            rtv_operation.setTextColor(ContextCompat.getColor(getContext(), R.color.common_title_text));
                            rtv_operation.setText(getString(R.string.follow_add));
                        }

                        rtv_operation.setTag(position);
                        rtv_operation.setOnClickListener(v -> {
                            int pos = (int) v.getTag();
                            UserAttentionBean uab = (UserAttentionBean) adapter.getItem(pos);
                            assert mPresenter != null;
                            if (uab.getIsAttention() == 1) {
                                //关注的类型:0-用户,1-店铺
                                ReqParamsAttentionCancel reqParamsAttentionCancel = new ReqParamsAttentionCancel();
                                reqParamsAttentionCancel.setType(0);
                                reqParamsAttentionCancel.setIds(Collections.singletonList(uab.getUserId()));
                                mPresenter.unFollow(reqParamsAttentionCancel);
                            } else {
                                ReqParamsAttentionAdd reqParamsAttentionAdd = new ReqParamsAttentionAdd();
                                reqParamsAttentionAdd.setType(0);
                                reqParamsAttentionAdd.setId(uab.getUserId());
                                mPresenter.follow(reqParamsAttentionAdd);
                            }
                        });
                    }
                };
                rv_follow_list.setAdapter(adapter);

                adapter.setOnItemClickListener((parent, view, position, id) -> {
                    Intent intent = new Intent(getContext(), PersonalHomePageActivity.class);
                    intent.putExtra("userId", String.valueOf(adapter.get(position).getUserId()));
                    intent.putExtra("type", 0);
                    ArmsUtils.startActivity(intent);
                });

                srl_follow_list.setOnRefreshLoadMoreListener2(new OnRefreshLoadMoreListener2() {
                    @Override
                    public void onLoadMore(@NonNull RefreshLayout refreshLayout, int curPageNo) {
                        // 加载更多
                        reqParams.setPage(curPageNo);
                        getBisDataList();
                    }

                    @Override
                    public void onRefresh(@NonNull RefreshLayout refreshLayout, int curPageNo) {
                        // 刷新
                        reqParams.setPage(curPageNo);
                        getBisDataList();
                    }
                });
                getBisDataList();
                break;
            }
            case 1: {
                adapter = new BaseRecyclerAdapter<UserAttentionBean>(R.layout.item_follow_store) {
                    @Override
                    protected void onBindViewHolder(SmartViewHolder holder, UserAttentionBean model, int position) {
                        holder.image(R.id.imv_store_head_portrait, model.getStoreLogo());
                        RoundTextView tv_store_is_closed = (RoundTextView) holder.findViewById(R.id.tv_store_is_closed);
//                        ImageView imv_level_icon = (ImageView) holder.findViewById(R.id.imv_level_icon);
                        TextView tv_store_name = (TextView) holder.findViewById(R.id.tv_store_name);
                        RoundTextView tv_store_type = (RoundTextView) holder.findViewById(R.id.tv_store_type);
                        TextView tv_store_score = (TextView) holder.findViewById(R.id.tv_store_score);
                        TextView tv_store_on_line = (TextView) holder.findViewById(R.id.tv_store_on_line);

                        holder.text(tv_store_on_line, model.getStoreName());
                        if (model.getIsShow() == 0) {//店铺状态:0-关闭,1-开启
                            tv_store_is_closed.setVisibility(View.VISIBLE);
                            tv_store_type.setVisibility(View.GONE);
//                            imv_level_icon.setVisibility(View.GONE);
                            tv_store_score.setVisibility(View.GONE);
                            tv_store_name.setTextColor(ContextCompat.getColor(Objects.requireNonNull(getContext()), R.color.content_second_color));
                            holder.text(tv_store_on_line, "");
                        } else {
                            tv_store_is_closed.setVisibility(View.GONE);
                            tv_store_type.setVisibility(View.VISIBLE);
//                            imv_level_icon.setVisibility(View.VISIBLE);
                            tv_store_score.setVisibility(View.GONE);//应产品的要求，屏蔽掉
                            tv_store_name.setTextColor(ContextCompat.getColor(Objects.requireNonNull(getContext()), R.color.common_title_text));
                            holder.text(tv_store_on_line, getString(R.string.store_closed_note));

//                            holder.image(imv_level_icon, model.getMemberLevelHeadImage());
                            holder.text(R.id.tv_store_type, model.getStoreRank());
//                            holder.text(R.id.tv_store_score, String.format(getString(R.string.follow_score_fm), model.getScore()));//应产品的要求，屏蔽掉
                            holder.text(R.id.tv_store_on_line, String.format(getString(R.string.follow_store_on_line_count_fm), model.getOnlineCount()));
                        }
                        RoundTextView rtv_operation = (RoundTextView) holder.findViewById(R.id.rtv_operation);
                        if (model.getIsAttention() == 1) {// 已关注
                            rtv_operation.getDelegate().setBackgroundColor(ContextCompat.getColor(Objects.requireNonNull(getContext()), R.color.color_AAAAAA));
                            rtv_operation.setTextColor(ContextCompat.getColor(getContext(), R.color.white));
                            rtv_operation.setText(getString(R.string.is_followed));
                        } else {
                            rtv_operation.getDelegate().setBackgroundColor(ContextCompat.getColor(Objects.requireNonNull(getContext()), R.color.color_F9D35A));
                            rtv_operation.setTextColor(ContextCompat.getColor(getContext(), R.color.common_title_text));
                            rtv_operation.setText(getString(R.string.follow_add));
                        }

                        rtv_operation.setTag(position);
                        rtv_operation.setOnClickListener(v -> {
                            int pos = (int) v.getTag();
                            UserAttentionBean uab = (UserAttentionBean) adapter.getItem(pos);
                            assert mPresenter != null;
                            if (uab.getIsAttention() == 1) {
                                //关注的类型:0-用户,1-店铺
                                ReqParamsAttentionCancel reqParamsAttentionCancel = new ReqParamsAttentionCancel();
                                reqParamsAttentionCancel.setType(1);
                                reqParamsAttentionCancel.setIds(Collections.singletonList(uab.getStoreId()));
                                mPresenter.unFollow(reqParamsAttentionCancel);
                            } else {
                                ReqParamsAttentionAdd reqParamsAttentionAdd = new ReqParamsAttentionAdd();
                                reqParamsAttentionAdd.setType(1);
                                reqParamsAttentionAdd.setId(uab.getStoreId());
                                mPresenter.follow(reqParamsAttentionAdd);
                            }
                        });
                    }
                };
                rv_follow_list.setAdapter(adapter);

                adapter.setOnItemClickListener((parent, view, position, id) -> {
                    Intent intent = new Intent(getContext(), MyStoreActivity.class);
                    intent.putExtra("userStoreId", String.valueOf(adapter.get(position).getStoreId()));
                    intent.putExtra("userId", String.valueOf(adapter.get(position).getUserId()));
                    ArmsUtils.startActivity(intent);
                });

                srl_follow_list.setOnRefreshLoadMoreListener2(new OnRefreshLoadMoreListener2() {
                    @Override
                    public void onLoadMore(@NonNull RefreshLayout refreshLayout, int curPageNo) {
                        // 加载更多
                        reqParams.setPage(curPageNo);
                        getBisDataList();
                    }

                    @Override
                    public void onRefresh(@NonNull RefreshLayout refreshLayout, int curPageNo) {
                        // 刷新
                        reqParams.setPage(curPageNo);
                        getBisDataList();
                    }
                });
                getBisDataList();
                break;
            }
        }
    }

    private void getBisDataList() {
        switch (tabFlag) {
            case 0:
                if (isCurrentUser) {
                    mPresenter.getFollowUserList4CurrentUserId(reqParams);
                } else {
                    mPresenter.getFollowUserList4OtherUserId(reqParams);
                }
                break;
            case 1:
                if (isCurrentUser) {
                    mPresenter.getFollowStoreList4CurrentUserId(reqParams);
                } else {
                    mPresenter.getFollowStoreList4OtherUserId(reqParams);
                }
                break;
        }
    }

    /**
     * 此方法是让外部调用使fragment做一些操作的,比如说外部的activity想让fragment对象执行一些方法,
     * 建议在有多个需要让外界调用的方法时,统一传Message,通过what字段,来区分不同的方法,在setData
     * 方法中就可以switch做不同的操作,这样就可以用统一的入口方法做不同的事
     * <p>
     * 使用此方法时请注意调用时fragment的生命周期,如果调用此setData方法时onCreate还没执行
     * setData里却调用了presenter的方法时,是会报空的,因为dagger注入是在onCreated方法中执行的,然后才创建的presenter
     * 如果要做一些初始化操作,可以不必让外部调setData,在initData中初始化就可以了
     *
     * @param data
     */

    @Override
    public void setData(Object data) {
    }


    @Override
    public void showLoading() {
        loadingDialog.show();
    }

    @Override
    public void hideLoading() {
        loadingDialog.dismiss();
    }

    @Override
    public void showMessage(@NonNull String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(@NonNull Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
    }

    @Override
    public void followSuccess() {
        showMessage(getString(R.string.success));
        reqParams.setPage(1);
        getBisDataList();
    }

    @Override
    public void unFollowSuccess() {
        showMessage(getString(R.string.success));
        reqParams.setPage(1);
        getBisDataList();
    }

    @Override
    public void getFollowUserList4UserIdSuccess(List<UserAttentionBean> list) {
        srl_follow_list.finishLoadMore();
        srl_follow_list.finishRefresh();
        if (list != null && !list.isEmpty()) {
            ViewExtensionKt.visible(empty, false);
            ViewExtensionKt.visible(rv_follow_list, true);
            if (ViewExtensionKt.isPullDown(srl_follow_list, list.size(), reqParams.getLimit())) {
                adapter.refresh(list);
            } else {
                adapter.loadMore(list);
            }
        } else {
            if (reqParams.getPage() > 1) {
                ViewExtensionKt.visible(empty, false);
                ViewExtensionKt.visible(rv_follow_list, true);
            } else {
                ViewExtensionKt.visible(empty, true);
                ViewExtensionKt.visible(rv_follow_list, false);
            }
        }
    }

    @Override
    public void getFollowStoreList4UserIdSuccess(List<UserAttentionBean> list) {
        srl_follow_list.finishLoadMore();
        srl_follow_list.finishRefresh();
        if (list != null && !list.isEmpty()) {
            ViewExtensionKt.visible(empty, false);
            ViewExtensionKt.visible(rv_follow_list, true);
            if (ViewExtensionKt.isPullDown(srl_follow_list, list.size(), reqParams.getLimit())) {
                adapter.refresh(list);
            } else {
                adapter.loadMore(list);
            }
        } else {
            if (reqParams.getPage() > 1) {
                ViewExtensionKt.visible(empty, false);
                ViewExtensionKt.visible(rv_follow_list, true);
            } else {
                ViewExtensionKt.visible(empty, true);
                ViewExtensionKt.visible(rv_follow_list, false);
            }
        }
    }

    @Override
    public void getListFailed() {
        srl_follow_list.finishLoadMore();
        srl_follow_list.finishRefresh();
        if (reqParams.getPage() > 1) {
            reqParams.setPage(reqParams.getPage() - 1);
        }
    }
}